package ev.operator;//need to add this line

import ev.data.*;//need to add this line
import java.util.ArrayList;
import java.util.Arrays;


public class cycle implements Crossover{
	public	ArrayList<Individual> cross(Individual a, Individual b){
		ArrayList<Individual> res = new ArrayList<Individual>();
		int[] parent1 = a.getList();
		int[] parent2 = b.getList();
		int len = parent1.length;
		int[][] child = new int[2][len];
		int[] flag = new int[len];
		for(int i = 0; i< len; i++){
			flag[i] = 0;
		}
		for(int i=0; i<len;){
			if(flag[i] == 1)
				break;
			flag[i] = 1;
			i = searchIndex(parent1, parent2[i]);
		}
		int index = 0;
		for(int i = 0; i < len; i++){
			if(flag[i] != 1){
				index = i;
				break;
			}
		}
		if(index == 0){
			Individual c1 = a.copy();
			Individual c2 = b.copy();
			res.add(c1);
			res.add(c2);
			return res;
		}
		for(int i = index; i<len;){
			if(flag[i] == 2)
				break;
			flag[i] = 2;
			i = searchIndex(parent1, parent2[i]);
		}
		for(int i = 0; i < len; i++){
			if(flag[i] == 1 || flag[i] == 0){
				child[0][i] = parent1[i];
				child[1][i] = parent2[i];
			}
			else if(flag[i] == 2){
				child[0][i] = parent2[i];
				child[1][i] = parent1[i];
			}
		}
		Individual child1 = new Individual(child[0]);
		Individual child2 = new Individual(child[1]);
		res.add(child1);
		res.add(child2);
		return res;
	}
	
	public int searchIndex(int[] data, int target){
		for(int i = 0; i<data.length; i++){
			if(data[i] == target)
				return i;
		}
		return -1;
	} 
}
